package com.lz.stock.controller;

import com.lz.stock.entity.TbStock;
import com.lz.stock.service.ITbStockService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.http.HttpMethod;
import com.lz.stock.entity.TbOrderDetail;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lz
 * @since 2024-08-29
 */
@RestController
@RequestMapping("/stock/tbStock")
public class TbStockController {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private ITbStockService stockService;

    @GetMapping("test1")
    public List<TbOrderDetail> findGoods(){
        String url = "http://order-service/order/list";
        //通过服务id调用服务提供者
        ResponseEntity<List<TbOrderDetail>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<TbOrderDetail>>() {}
        );
        return response.getBody();
    }
    @GlobalTransactional(rollbackFor = {Exception.class})
    @PostMapping("/subtractStock")
    public TbStock subtractStock(){
        TbStock stock = stockService.getById(1);
        stock.setStock(stock.getStock()-1);
        stockService.updateById(stock);
//        if (true){
//            throw new RuntimeException("测试分布式事务");
//        }
        String url = "http://order-service/order/createOrder";
        ResponseEntity<TbOrderDetail> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                null,
                new ParameterizedTypeReference<TbOrderDetail>() {}
        );

        return stock;
    }

}
